package com.gddb.xwj.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author xuwj
 * @Description: Cookie工具类
 * @CreateTime 2020/1/19 2:09
 * @Version 1.0
 */
public class CookieUtil {
    private CookieUtil() {
    }

    /**
     * 添加cookie
     *
     * @param resp
     * @param cookieName
     * @param cookieValue
     * @param maxAge
     */
    public static void addCookie(HttpServletResponse resp, String cookieName, String cookieValue, int maxAge) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setPath("/");
        if (maxAge > 0) {
            cookie.setMaxAge(maxAge);
        }
        resp.addCookie(cookie);
    }

    /**
     * 删除cookie
     *
     * @param resp
     * @param cookieName
     */
    public static void removeCookie(HttpServletResponse resp, String cookieName) {
        Cookie cookie = new Cookie(cookieName, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }

    /**
     * 获取cookie
     *
     * @param req
     * @param cookieName
     * @return
     */
    public static String getCookie(HttpServletRequest req, String cookieName) {
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
